package com.servlet;

import com.bean.User;
import com.google.gson.Gson;
import com.service.UserService;
import com.service.impl.UserServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet("/user.do")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    protected void upPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        String username = (String) req.getParameter("username");
        String oldpass = (String) req.getParameter("oldpass");
        String newpass = (String) req.getParameter("newpass");
        User user = new User();

        User user1 = userService.existsUsername(username);
        user1.getUserpassword();

        if (oldpass.equals( user1.getUserpassword())) {
            user.setUserName(username);
            user.setUserpassword(newpass);

            userService.updateUserspasswords(user);
            req.setAttribute("msg", "修改成功");
        } else {
            req.setAttribute("msg", "修改失败");
        }
        req.getRequestDispatcher("/PersonalCenter.jsp").forward(req, resp);
    }

    /**
     * 修改个人信息
     */
    protected void message(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        String username = (String) req.getParameter("username");
        String email = (String) req.getParameter("email");
        User user = new User();
        user.setUseremail(email);
        user.setUserName(username);

        int i = userService.updateUsers(user);
        if (i > 0) {
            req.setAttribute("msg", "保存成功");
        } else {
            req.setAttribute("msg", "保存失败");
        }
        req.getRequestDispatcher("/PersonalCenter.jsp").forward(req, resp);


    }


    /**
     * 处理登录的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        //  1、获取请求的参数
//        req.getSession().removeAttribute("user");
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String username = req.getParameter("userName");
        String password = req.getParameter("userpassword");
//        String userphone =req.getParameter("userphone");
        // 调用 userService.login()登录处理业务
        User loginUser = userService.login(new User(null, username, password, null, null, null, null));
        Map<String, Object> map = new HashMap<String, Object>();
        Gson gson = new Gson();
        // 如果等于null,说明登录 失败!
        if (loginUser == null) {
            // 把错误信息，和回显的表单项信息，保存到Request 域中
//            req.setAttribute("msg", "咦！这都输入错了");
            map.put("msg", "咦！这都输入错了");
            String s = gson.toJson(map);
            System.out.println(s);
            resp.getWriter().write(s);

//            req.getSession().setAttribute("userName", username);

        } else {
            // 登录 成功
            //跳到成功页面 login_success.html
            req.getSession().setAttribute("user", loginUser);
            map.put("msg", "successed");
            String s = gson.toJson(map);
            System.out.println(s);
            resp.getWriter().write(s);

        }
    }

    /**
     * 处理注册的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        //  1、获取请求的参数
        String userName = req.getParameter("userName");
        String userpassword = req.getParameter("userpassword");
        String useremail = req.getParameter("useremail");
        String userphone = req.getParameter("userphone");
        String userpic = req.getParameter("userpic");
        String code = req.getParameter("code");//验证码
//        2、检查 验证码
        // 获取Session 中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        // 删除 Session 中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        if (token.equalsIgnoreCase(code)) {
//        3、检查 用户名是否可用
            if (userService.existsUsernameemail(userName, useremail)) {

                // 把回显信息，保存到Request 域中
                req.setAttribute("errorMsg", "用户名或邮箱已存在！！");
                req.setAttribute("userName", userName);
                req.setAttribute("userpassword", userpassword);
                req.setAttribute("useremail", useremail);
                req.setAttribute("userphone", userphone);
                req.setAttribute("userpic", userpic);
//                创建一个Session对象，保存信息
                HttpSession session = req.getSession();
                session.setAttribute("userName", userName);
                session.setAttribute("userpassword", userpassword);
                session.setAttribute("useremail", useremail);
                session.setAttribute("userphone", userphone);
                session.setAttribute("userpic", userpic);
                session.setAttribute("code", code);
//        跳回注册页面
                req.getRequestDispatcher("page/zhuce/signin.jsp").forward(req, resp);
            } else {
                //      可用
//                调用Sservice 保存到数据库
                userService.registUser(new User(null, userName, userpassword, useremail, userphone, 1, null));
//
//        跳到注册成功页面 regist_success.jsp
                req.getRequestDispatcher("index1.jsp").forward(req, resp);
            }
        } else {
            // 把回显信息，保存到Request 域中
            req.setAttribute("errorMsg", "验证码错误！！");
            req.setAttribute("userName", userName);
            req.setAttribute("useremail", useremail);

            HttpSession session = req.getSession();
            session.setAttribute("userName", userName);
            session.setAttribute("userpassword", userpassword);
            session.setAttribute("useremail", useremail);
            session.setAttribute("userphone", userphone);
            session.setAttribute("userpic", userpic);
            session.setAttribute("code", code);
            req.getRequestDispatcher("page/zhuce/signin.jsp").forward(req, resp);
        }


    }

    /**
     * 注销
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        //1.销毁Session中用户登陆的信息
        req.getSession().invalidate();
        //2.重定向到首页
        resp.sendRedirect("/index.jsp");
    }
}
